package mathsys;

import java.io.*;
import java.util.*;

public class MathExerciseGeneratorV4 {
    // 存储已生成的算式，用于去重
    private static Set<String> generatedExpressions = new HashSet<>();

    // 生成指定范围内的随机整数
    private static int getRandomNumber(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    // 生成带答案的加减法算式（确保不重复）
    private static Map.Entry<String, Integer> generateUniqueExercise() {
        while (true) {
            int num1 = getRandomNumber(0, 100);
            int num2 = getRandomNumber(0, 100);
            int operator = getRandomNumber(0, 1); // 0:加法, 1:减法
            String expression;
            int result;

            if (operator == 0) { // 加法
                if (num1 + num2 > 100) continue;
                // 标准化加法表达式，避免3+5和5+3被视为不同
                if (num1 > num2) {
                    int temp = num1;
                    num1 = num2;
                    num2 = temp;
                }
                expression = num1 + " + " + num2;
                result = num1 + num2;
            } else { // 减法
                if (num1 < num2) continue;
                expression = num1 + " - " + num2;
                result = num1 - num2;
            }

            // 检查是否已存在该算式
            if (!generatedExpressions.contains(expression)) {
                generatedExpressions.add(expression);
                return new AbstractMap.SimpleEntry<>(expression, result);
            }
        }
    }

    // 生成HTML文件
    private static void generateHTML(List<Map.Entry<String, Integer>> exercises) {
        try (PrintWriter out = new PrintWriter(new FileWriter("math_exercises_v0.4.html"))) {
            out.println("<!DOCTYPE html>");
            out.println("<html lang=\"zh-CN\">");
            out.println("<head>");
            out.println("    <meta charset=\"UTF-8\">");
            out.println("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
            out.println("    <title>加减法口算练习系统-v0.4</title>");
            out.println("    <style>");
            out.println("        body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }");
            out.println("        h1 { color: #333; text-align: center; }");
            out.println("        .stats { text-align: center; color: #666; margin: 10px 0 20px; }");
            out.println("        .exercise-container { margin: 30px auto; display: grid;");
            out.println("            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));");
            out.println("            gap: 20px; }");
            out.println("        .exercise { font-size: 18px; padding: 15px; border: 1px solid #ddd;");
            out.println("            border-radius: 5px; background-color: #f9f9f9; }");
            out.println("        .addition { border-left: 4px solid #4CAF50; }");
            out.println("        .subtraction { border-left: 4px solid #2196F3; }");
            out.println("        .input-group { margin: 10px 0; display: flex; align-items: center; gap: 10px; }");
            out.println("        input { width: 60px; padding: 8px; font-size: 16px; text-align: center; }");
            out.println("        button.check-btn { padding: 6px 12px; background-color: #555; color: white;");
            out.println("            border: none; border-radius: 4px; cursor: pointer; }");
            out.println("        button.check-btn:hover { background-color: #333; }");
            out.println("        .feedback { margin-top: 10px; padding: 8px; border-radius: 4px; display: none; }");
            out.println("        .correct { background-color: #dff0d8; color: #3c763d; display: block; }");
            out.println("        .incorrect { background-color: #f2dede; color: #a94442; display: block; }");
            out.println("        .empty { background-color: #fcf8e3; color: #8a6d3b; display: block; }");
            out.println("        .submit-all { text-align: center; margin: 30px; }");
            out.println("        #submitAllBtn { padding: 10px 20px; font-size: 18px; background-color: #2196F3;");
            out.println("            color: white; border: none; border-radius: 4px; cursor: pointer; }");
            out.println("        #submitAllBtn:hover { background-color: #0b7dda; }");
            out.println("    </style>");
            out.println("    <script>");
            // 检查单个答案
            out.println("        function checkAnswer(index, correctAnswer) {");
            out.println("            const input = document.getElementById('answer_' + index);");
            out.println("            const feedback = document.getElementById('feedback_' + index);");
            out.println("            const userAnswer = input.value.trim();");
            out.println("");
            out.println("            // 清空之前的反馈样式");
            out.println("            feedback.classList.remove('correct', 'incorrect', 'empty');");
            out.println("");
            out.println("            if (userAnswer === '') {");
            out.println("                feedback.textContent = '未填写答案，正确答案是: ' + correctAnswer;");
            out.println("                feedback.classList.add('empty');");
            out.println("            } else if (parseInt(userAnswer) === correctAnswer) {");
            out.println("                feedback.textContent = '答对了，真棒！';");
            out.println("                feedback.classList.add('correct');");
            out.println("            } else {");
            out.println("                feedback.textContent = '答错了，正确答案是: ' + correctAnswer;");
            out.println("                feedback.classList.add('incorrect');");
            out.println("            }");
            out.println("        }");
            out.println("");
            // 批量提交所有答案
            out.println("        function submitAllAnswers() {");
            out.println("            const total = " + exercises.size() + ";");
            out.println("            for (let i = 0; i < total; i++) {");
            out.println("                const correctAnswer = parseInt(document.getElementById('correct_' + i).value);");
            out.println("                checkAnswer(i, correctAnswer);");
            out.println("            }");
            out.println("        }");
            out.println("    </script>");
            out.println("</head>");
            out.println("<body>");
            out.println("    <h1>加减法口算练习系统-v0.4</h1>");

            // 统计加减法数量
            long additionCount = exercises.stream()
                    .filter(e -> e.getKey().contains("+"))
                    .count();
            long subtractionCount = exercises.size() - additionCount;

            out.println("    <div class=\"stats\">");
            out.println("        共" + exercises.size() + "题（加法：" + additionCount + "题，减法：" + subtractionCount + "题）");
            out.println("    </div>");

            out.println("    <div class=\"exercise-container\">");

            // 循环生成习题
            int index = 0;
            for (Map.Entry<String, Integer> exercise : exercises) {
                String expression = exercise.getKey();
                int answer = exercise.getValue();
                String typeClass = expression.contains("+") ? "addition" : "subtraction";

                out.println("        <div class=\"exercise " + typeClass + "\">");
                out.println("            <span class=\"number\">" + (index + 1) + ". </span>");
                out.println("            <span class=\"expression\">" + expression + " = </span>");
                out.println("            <div class=\"input-group\">");
                out.println("                <input type=\"number\" id=\"answer_" + index + "\" placeholder=\"?\">");
                out.println("                <button class=\"check-btn\" onclick=\"checkAnswer(" + index + ", " + answer + ")\">检查</button>");
                out.println("            </div>");
                out.println("            <div id=\"feedback_" + index + "\" class=\"feedback\"></div>");
                // 隐藏的正确答案存储
                out.println("            <input type=\"hidden\" id=\"correct_" + index + "\" value=\"" + answer + "\">");
                out.println("        </div>");
                index++;
            }

            out.println("    </div>");

            // 批量提交按钮
            out.println("    <div class=\"submit-all\">");
            out.println("        <button id=\"submitAllBtn\" onclick=\"submitAllAnswers()\">提交所有答案</button>");
            out.println("    </div>");

            out.println("</body>");
            out.println("</html>");

            System.out.println("习题已生成，请打开 math_exercises_v0.4.html 文件查看");
        } catch (IOException e) {
            System.err.println("生成HTML文件时出错: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        int totalCount = 50;
        if (totalCount < 2) {
            System.err.println("题目数量不能少于2道");
            return;
        }

        List<Map.Entry<String, Integer>> exercises = new ArrayList<>();
        generatedExpressions.clear();

        // 确保至少有1道加法和1道减法
        while (true) {
            Map.Entry<String, Integer> exercise = generateUniqueExercise();
            if (exercise.getKey().contains("+")) {
                exercises.add(exercise);
                break;
            }
        }
        while (true) {
            Map.Entry<String, Integer> exercise = generateUniqueExercise();
            if (exercise.getKey().contains("-")) {
                exercises.add(exercise);
                break;
            }
        }

        // 生成剩余题目
        for (int i = 2; i < totalCount; i++) {
            exercises.add(generateUniqueExercise());
        }

        // 打乱题目顺序
        Collections.shuffle(exercises);

        // 生成HTML页面
        generateHTML(exercises);
    }
}